package pro.seac.twitter.web.view.component;

import static pro.seac.twitter.web.UIUtils.newTable;

import java.util.List;

import pro.seac.twitter.application.dto.UserViewEntry;
import pro.seac.twitter.web.view.BaseView;
import pro.seac.twitter.web.view.Gravatar;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.server.ExternalResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.themes.Reindeer;

public class UserTable extends CustomComponent {
	private static final long serialVersionUID = 1L;
	private Table userTable;
	private BeanItemContainer<UserViewEntry> userContainer;

	public UserTable() {
		super();
		initContent();
	}

	protected void initContent() {
		userContainer = new BeanItemContainer<UserViewEntry>(UserViewEntry.class);
		ActionsColumnGenerator columnGenerator = new ActionsColumnGenerator();
		// @formatter:off
		userTable = newTable().
				withColumn("avatar", 50, columnGenerator).
				withContainer(userContainer, new String[] { "userName", "createdDate", "name"}).
				withColumn("userName", 150, null).
				withColumn("createdDate", 150, null).
				withColumn("name", -1, null).
				withColumn("actions", 100, columnGenerator).
				build();
		// @formatter:on
		setCompositionRoot(userTable);
	}

	public class ActionsColumnGenerator implements ColumnGenerator {
		private static final long serialVersionUID = 1L;

		@Override
		public Object generateCell(Table source, Object itemId, Object columnId) {
			final UserViewEntry user = (UserViewEntry) itemId;
			if ("actions".equals(columnId)) {
				Button button = new Button("poka\u017C", new ClickListener() {
					private static final long serialVersionUID = 1L;

					@Override
					public void buttonClick(ClickEvent event) {
						BaseView.goToUsersProfileView(user.getUserName());
					}
				});
				button.setStyleName(Reindeer.BUTTON_SMALL);
				return button;
			} else if ("avatar".equals(columnId)) {
				Embedded avatar = new Embedded(null, new ExternalResource(Gravatar.getAvatarUrl(user.getEmail(), "24")));
				avatar.setWidth("24px");
				avatar.setHeight("24px");
				return avatar;
			}
			return null;
		}
	}

	public void refreshUsers(List<UserViewEntry> entries) {
		userContainer.removeAllItems();
		userContainer.addAll(entries);
	}
}
